<template>
    <van-popup v-model="isShow" position="bottom" :close-on-click-overlay="false" :lazy-render="false" :lock-scroll="true" :overlay="true">
        <div class="spec_body">
            <div class="spec_top">
                <img :src="selectedImg" alt="" />
                <div class="text">
                    <div class="current" >
                        {{ selectedPrice.price| moneyFmt }}
                    </div>
                    <div class="stock">库存{{ selectedStock }}件</div>
                    <div class="choice">{{ specMsg }}</div>
                </div>
                <svg aria-hidden="true" class="close" @click.stop="close">
                    <use xlink:href="#icon-close"></use>
                </svg>
            </div>
            <div class="line1"></div>
            <mini-spec :proContent="proContent" ref="spec" @getChoose="getShowMsg" @findSku="findSku">
                <div class="spec_num">
                    <span>数量</span>
                    <div class="control">
                        <num-control :num="buyNum" :isCart="false" @changeNumber="changeNumber"/>
                    </div>
                </div>
            </mini-spec>
            <div class="line1"></div>
            <div class="spec_bottom">
                <div class="confirm"  v-if="operation === 'buy'" @click="chooseDone(operation)">选好了</div>
                <div class="buy" v-if="operation === 'initiate'" @click="chooseDone(operation)">发起拼团</div>
                <div class="buy"  v-if="operation === 'participate'" @click="chooseDone(operation)">参与拼团</div>
            </div>
        </div>
    </van-popup>
</template>

<script>
    import NumControl from '../common/num-control';
    import MiniSpec from "./mini-spec";
    import API from '@/request/api';

    export default {
        name: 'group-spec',
        data() {
            return{
                isShow: false,//组件是否展示
                opera: '', // 选择的功能按钮（选好了，加入购物车，立即购买）
                chooseSku: '',
                specMsg: '', //提示信息,
                buyNum: 1,
                groupid: this.$route.query.groupid ? this.$route.query.groupid : '1',
            }
        },
        props:{
            proContent:{
                type:Object
            },
            operation: {
                type: String
            }
        },
        created(){
        },
        methods:{
            show() { //组件显示
                if(this.selectedStock == 0){
                    this.$toast('该商品已售罄')
                    this.isShow = false;
                } else {
                    // 获取商品详情（全文）
                    this.request.get(API.groupPartVerify, {
                        gid: this.proContent.gid,
                        groupid: this.groupid
                    }).then((res) => {
                        console.log('groupPartVerify', res);
                        if(!res.status){
                            this.$toast({
                                message: res.msg
                            });
                            return;
                        }
                        this.isShow = true;
                        this.$refs.spec.refresh()
                    }).catch((err) => {
                        console.error('groupPartVerify', err);
                    });
                }
            },
            close() {
                if (this.chooseSku !== '' && this.opera !== '') {
                    this.$emit('chooseDone', this.chooseSku, this.opera);
                }
                this.$emit('showSpecMsg', this.specMsg);
                this.opera = '';
                this.isShow = false;
            },
            changeNumber(num) {
                this.buyNum = num;
            },
            //获取显示所选情况
            getShowMsg(selectArr){
                let selectVal = Object.values(selectArr);
                let msg ='';
                let emptyArr = []
                if(selectVal.includes('')){
                    for (let k in selectArr){
                        if (selectArr[k] === ''){
                            emptyArr.push(k)
                        }
                    }
                    msg = '请选择：'+emptyArr.join(',')
                    this.chooseSku =''
                } else {
                    msg = '已选择：' + selectVal.join(',')
                }
                this.specMsg = msg;
                this.$emit('showSpecMsg', this.specMsg);
            },
            findSku(buyid){
                this.proContent.sku.filter((item)=>{
                    if(item.buyid === buyid){
                        this.chooseSku = item
                    }
                })
            },
            chooseDone(opera) {
                if (this.chooseSku !== '') {
                    if(this.buyNum <= this.chooseSku.stock){
                        // 拼团验证
                        this.request.get(API.groupPartVerify, {
                            gid: this.proContent.gid,
                            groupid: this.groupid,
                            num: this.buyNum
                        }).then((res) => {
                            console.log('groupPartVerify', res);
                            if(!res.status){
                                this.$toast({
                                    message: res.msg
                                });
                                return;
                            }
                            this.opera = opera;
                            this.chooseSku.count = this.buyNum;
                            this.close();
                        }).catch((err) => {
                            console.error('groupPartVerify', err);
                        });
                    } else {
                        this.$toast('库存不足，请重新选择');
                        this.buyNum = this.chooseSku.stock
                    }

                } else {
                    this.$toast(this.specMsg);
                }
            },
        },
        computed: {
            selectedImg(){
                if (this.chooseSku) {
                    return this.chooseSku.pic;
                }
                if (this.proContent && this.proContent.sku) {
                    return this.proContent.pic
                }
            },
            selectedStock() {
                if (this.chooseSku) {
                    return this.chooseSku.stock;
                }
                if (this.proContent && this.proContent.sku) {
                    ///无选中sku库存求和
                    return this.proContent.sku.reduce((result, item) => {
                        return result + item.stock;
                    }, 0);
                }
                return 0;
            },
            selectedPrice() {
                let moneyData = {};
                if (this.chooseSku) {
                    moneyData.price = this.chooseSku.price;
                    moneyData.deduction = this.chooseSku.deduction;
                    return moneyData;
                    // return this.chooseSku.price;
                }
                if (this.proContent && this.proContent.sku) {
                    // moneyData.price = this.proContent.price;
                    // moneyData.deduction = this.proContent.deduction;
                    // return moneyData;
                    //无选中sku求价格最低
                    const priceList = this.proContent.sku.map((item) => {
                        return item.price;
                    });
                    moneyData.price = Math.min(...priceList);
                    return moneyData;
                }
                return 0;
            }
        },
        watch: {},
        components: {
            MiniSpec,
            NumControl
        }
    };
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    @import '~@/assets/main.styl'

    .van-popup {
        border-top-left-radius main-radius
        border-top-right-radius main-radius
    }

    .spec_body {
        position relative
        margin smallMargin smallMargin
        overflow-x hidden
        .spec_num {
            width vw(350)
            flex-x()
            position relative
            margin-top smallMargin
            word-vw(word16, gray3)
        }
    }

    .line1 {
        line()
        position relative
        margin titleMargin 0
    }

    .spec_top {
        width vw(355)
        height vw(100)

        img {
            float left
            width vw(100)
            height vw(100)
        }

        .text {
            float left
            margin-left middleMargin
            width vw(200)
            height vw(100)
        }

        .close {
            width vw(14)
            height vw(14)
            fill gray3
            position absolute
            right 0
        }

        .current {
            word-vw(word14, gray3)
            height vw(19)
            line-height vw(19)
            color main-color
            .earn {
                margin-left smallMargin
            }

            .change {
                color main-color
            }
        }

        .stock {
            word-vw(word14, gray9)
            height vw(19)
            line-height vw(19)
            margin-top vw(15)
        }

        .choice {
            word-vw(word14, gray9)
            margin-top middleMargin
        }

    }

    .spec_bottom {
        /*margin-top smallMargin*/
        display flex
        height vw(50)
        align-items center
        justify-content center
        background-color #fff
        font-size word16
        .cart {
            secondary-hollow()
        }
        .buy {
            margin-left middleMargin
            secondary-solid()
        }
        .confirm {
            flex 0 1 auto
            middle-solid()
            word-vw(word16, gary9)
        }
    }
    .title {
        word-vw(word12, gray3)
        margin-left bigMargin
        height vw(16)
        line-height vw(16)
    }

    .subtitle {
        word-vw(word12, gray9)
        margin-left bigMargin
        margin-top titleMargin
        height vw(16)
        line-height vw(16)
    }
</style>
